package com.jinlejia.bbs.ui.gambit;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jinlejia.bbs.R;
import com.jinlejia.bbs.adapter.GambitAdapter;
import com.jinlejia.bbs.bean.GambitListBean;
import com.jinlejia.bbs.bean.base.InformationBean;
import com.jinlejia.bbs.bean.base.TopicBean;
import com.jinlejia.bbs.databinding.BbsFragmentGambitIndexBinding;
import com.jinlejia.bbs.logic.GambitIndexLogic;
import com.jinlejia.bbs.logic.LikeFunLogic;
import com.jinlejia.bbs.ui.fun.BBSAskActivity;
import com.jinlejia.bbs.ui.fun.BBSSearchActivity;
import com.jinlejia.bbs.ui.reply.BBSReplyDetailActivity;
import com.jinlejia.bbs.widget.mp3.AudioController;
import com.jinlejia.bbs.widget.recycler.PullInterface;

/**
 * 话题-话题标签页
 */
public class BBSGambitIndexFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, GambitIndexLogic.LogicCallBack, PullInterface.LoadMoreListener,SearchHelper2 {
    private BbsFragmentGambitIndexBinding binding;
    private GambitListBean data = new GambitListBean();
    private GambitIndexLogic logic;
    private LikeFunLogic likeFunLogic;
    private View view;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view==null){
            view = inflater.inflate(R.layout.bbs_fragment_gambit_index, container, false);
            binding = DataBindingUtil.bind(view);
        }
        if (logic==null){
            logic = new GambitIndexLogic(this,data,this);
        }
        if (likeFunLogic==null){
            likeFunLogic = new LikeFunLogic(this);
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        initView();
        return view;
    }

    private AudioController audioController;
    @Override
    public void onResume() {
        super.onResume();
//        onRefresh();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        audioController = new AudioController(getContext());
    }

    @Override
    public void onDetach() {
        if (audioController!=null){
            audioController.release();
        }
        super.onDetach();
    }

    @Override
    public void onPause() {
        if (audioController!=null){
            audioController.release();
        }
        super.onPause();
    }

    private GambitAdapter adapter;
    private void initView() {
        binding.swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);
        binding.swipeRefreshLayout.setOnRefreshListener(this);

        binding.askButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(getContext(), BBSAskActivity.class);
                startActivityForResult(intent,askRequestId);
            }
        });
        binding.searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length()>0){
//                    binding.closeImageView.setVisibility(View.VISIBLE);
                }else {
                    binding.closeImageView.setVisibility(View.GONE);
                }
            }
        });
        binding.closeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.searchEditText.setText(null);
                onRefresh();
            }
        });
        binding.searchEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchGambit();
            }
        });
        if (adapter==null){
            adapter = new GambitAdapter(getContext(),audioController,binding.recyclerView);
            adapter.setGambitOnClickListener(new GambitAdapter.GambitOnClickListener() {
                @Override
                public void onClickTopic(TopicBean bean) {
                    Intent intent = new Intent();
                    intent.putExtra("topic",bean);
                    intent.setClass(getContext(), BBSReplyDetailActivity.class);
                    startActivityForResult(intent,replyRequestId);
                }
            });
            adapter.setHotListener(new GambitAdapter.HotListener() {
                @Override
                public void onHot() {
                    Intent intent = new Intent();
                    intent.setClass(getContext(), BBSHotGambitActivity.class);
                    startActivityForResult(intent,hotRequestId);
                }
            });
            adapter.setLikeOnClickListener(new GambitAdapter.LikeOnClickListener() {
                @Override
                public void onClickLike(TopicBean topic, final InformationBean information, final int position) {
                    likeFunLogic.execute(information.getAnswerCode(), new LikeFunLogic.LogicCallBack() {
                        @Override
                        public void onResult(boolean likeState) {
                            information.setOwnLike(likeState);
                            if (likeState){
                                information.setLikeCount(information.getLikeCount()+1);
                            }else {
                                information.setLikeCount(information.getLikeCount()-1);
                            }
                            adapter.notifyItemChanged(position);
                        }
                    });

                }
            });
            LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            binding.recyclerView.setAdapter(adapter);
            binding.recyclerView.setLayoutManager(layoutManager);
            binding.recyclerView.setAutoLoadMoreListener(this);
            binding.swipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    binding.swipeRefreshLayout.setRefreshing(true);
                    String searchText = binding.searchEditText.getText().toString();
                    logic.refresh(searchText);
                }
            });
        }


    }

    private int searchRequestId = 10;
    private int askRequestId = 11;
    private int replyRequestId = 12;
    private int hotRequestId = 13;
    private void searchGambit(){
        Intent intent = new Intent();
        intent.setClass(getContext(), BBSSearchActivity.class);
        startActivityForResult(intent,searchRequestId);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==searchRequestId && resultCode == Activity.RESULT_OK){
            String name = data.getStringExtra("name");
            searchInit(name);
        }else if (requestCode==askRequestId && resultCode==Activity.RESULT_OK){
            onRefresh();
        }else if (replyRequestId==requestCode && resultCode==Activity.RESULT_OK){
            onRefresh();
        }else if (hotRequestId==requestCode && resultCode==Activity.RESULT_OK){
            onRefresh();
        }
    }


    @Override
    public void onRefresh() {
        binding.swipeRefreshLayout.setRefreshing(true);
        String searchText = binding.searchEditText.getText().toString();
        logic.refresh(searchText);
    }

    @Override
    public void onResult(boolean hasNextPage) {
        adapter.initData(data);
        binding.swipeRefreshLayout.setRefreshing(false);
        if (!hasNextPage){
            binding.recyclerView.setAutoLoadMoreListener(null);
        }else {
            binding.recyclerView.setAutoLoadMoreListener(this);
        }
        binding.recyclerView.getAdapter().notifyDataSetChanged();
    }

    @Override
    public void onLoadMore() {
        binding.swipeRefreshLayout.setRefreshing(true);
        String searchText = binding.searchEditText.getText().toString();
        logic.load(searchText);
    }

    @Override
    public void searchInit(final String name) {
        binding.searchEditText.setText(name);
        onRefresh();
    }
}
